<?php

namespace api\modules\common\controllers;

use api\controllers\OnAuthController;
use api\modules\common\services\UploadService;
use common\helpers\CommonHelper;
use common\helpers\EncryptHelper;
use Yii;

/**
 * 文件
 *
 * Class FileController
 * @package api\modules\common\controllers
 */
class FileController extends OnAuthController
{
    public $modelClass = '';

    /**
     * 不用进行登录验证的方法
     *
     * 例如： ['index', 'update', 'create', 'view', 'delete']
     * 默认全部需要验证
     *
     * @var array
     */
    protected $authOptional = ['index'];

    /**
     * @api {post} /common/file/upload 上传文件
     * @apiName upload
     * @apiGroup File
     *
     * @apiBody {String} site               站点【工具：tool、内容：content】
     * @apiBody {String} module             模块【工具：nav、内容：index】
     * @apiBody {File}   file               文件信息【file or base64_file 二选一】
     * @apiBody {String} base64_file        base64信息流【file or base64_file 二选一】
     * @apiBody {Object} base64_orgin       base64源文件信息【base64上传必传{type: 'image/jpeg', name: 'xxx.type', size: 12300}】
     * @apiBody {Number} file_status        是否直接上传到正式目录【1是、0否，默认0】
     * @apiBody {String} min                生成min缩略图的规格【width,height => 300,300】
     * @apiBody {String} max                生成max缩略图的规格【width,height => 300,300】
     *
     * @apiSuccess {Object} data            返回内容
     * @apiSuccess {String} data.file       文件【传参取该参数，页面渲染取url】
     * @apiSuccess {Number} data.status     状态
     * @apiSuccess {String} data.url        url
     *
     */
    public function actionUpload()
    {
//        header('Access-Control-Allow-Origin:*');
//        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        try {
            $params = Yii::$app->request->post();
            $params['file'] = $_FILES['file'] ?? ($params['base64_file'] ?? []);
            
            return UploadService::upload($params);
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     * @apiIgnore
     * @api {post} /common/file/move 转移正式目录
     * @apiName move
     * @apiGroup File
     *
     * @apiBody {String} site                          站点【不传，则默认'default'】
     * @apiBody {String} module                        模块【不传，则默认'default'】
     * @apiBody {Array}  file                          文件名【兼容string 多个用','分割】
     *
     * @apiSuccess {Object} data                        返回内容
     *
     */
    public function actionMove()
    {
        $param = Yii::$app->request->post();

        return UploadService::move($param);
    }

    /**
     * @apiIgnore
     * @api {post} /common/file/delete 删除图片
     * @apiName delete
     * @apiGroup File
     *
     * @apiBody {String} site                          站点【不传，则默认'default'】
     * @apiBody {String} module                        模块【不传，则默认'default'】
     * @apiBody {Array}  file                          文件名【兼容string 多个用','分割】
     *
     * @apiSuccess {Object} data                        返回内容
     *
     */
    public function actionDelete()
    {
        $param = Yii::$app->request->post();

        return UploadService::delete($param);
    }

    /**
     * @api {get} /common/file/index 加载图片
     * @apiName index
     * @apiGroup File
     *
     * @apiParam {String} site                          站点【不传，则默认'default'】
     * @apiParam {String} module                        模块【不传，则默认'default'】
     * @apiParam {String} file                          文件名
     * @apiParam {Number} min                           显示小图【1是、0否】
     * @apiParam {Number} max                           显示大图【1是、0否】
     * @apiParam {String} time                          随机码
     *
     * @apiSuccess {Object} data                        返回内容
     */
    public function actionIndex()
    {
        $params = Yii::$app->request->get();

        $uploadService = new UploadService();
        $fileInfo =  $uploadService->loadFile($params);
        if (!$fileInfo['file_path']) {
            return CommonHelper::api(422, '图片不存在');
        }
        $t = $params['time'] ?? '';
        $url = $fileInfo['relative_file_path'];
        $url = $t ? $url."?{$t}" : $url;
        Header('location:'. $url);
//            Header("Content-type: {$fileInfo['file_type']}; charset: utf8");
//            echo file_get_contents($fileInfo['file_path']);
        exit();
    }

    /**
     * @api {get} /common/file/download 下载附件
     * @apiName download
     * @apiGroup File
     *
     *
     * @apiSuccess {Object} data                        返回内容
     */
    public function actionDownload()
    {
        $params = Yii::$app->request->get();
        $playload = $params['playload'] ?? '';

        try {
            $res = EncryptHelper::decodeFileParams($playload);
        } catch (\Exception $e) {
            return CommonHelper::api(422, '参数异常');
        }

        if ($res['aud'] != Yii::$app->user->identity->member_id) {
            return CommonHelper::api(422, '身份异常！');
        }
        if ($res['iat'] + Yii::$app->params['download_expire'] < time()) {
            return CommonHelper::api(422, '链接失效！');
        }

        $uploadService = new UploadService();
        $fileInfo =  $uploadService->loadFile((array)$res['file_info']);
        if (!$fileInfo['file_path']) {
            return CommonHelper::api(422, '图片不存在');
        }

        return Yii::$app->response->sendFile($fileInfo['file_path'], $fileInfo['file_name']);
    }

    /**
     * @apiIgnore
     * @api {get} /common/file/qrcode 生成二维码
     * @apiName qrcode
     * @apiGroup File
     *
     * @apiParam {String} text                          二维码内容
     *
     * @apiSuccess {Object} data                        返回内容
     *
     */
//    public function actionQrcode()
//    {
//        $param = Yii::$app->request->get();
//        $param['text'] = $param['text'] ?? '';
//
//        // Create a basic QR code
//        $qrCode = new QrCode($param['text']);
//        $qrCode->setSize(300);
//
//        // Set advanced options
//        $qrCode->setWriterByName('png');
//        $qrCode->setMargin(10);
//        $qrCode->setEncoding('UTF-8');
//        $qrCode->setErrorCorrectionLevel(ErrorCorrectionLevel::QUARTILE());
//        $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);
//        /*$qrCode->setLabel('Scan the code', 16, './fonts/msyh.ttc', LabelAlignment::CENTER());
//        $qrCode->setLogoPath('../uploadfile/comic/bg/2020/02/23/202002231931373htyB1.png');
//        $qrCode->setLogoWidth(80);
//        $qrCode->setLogoSize(80, 50);*/
//        $qrCode->setRoundBlockSize(true);
//        $qrCode->setValidateResult(false);
//        $qrCode->setWriterOptions(['exclude_xml_declaration' => true]);
//
//        // Directly output the QR code
//        header('Content-Type: '.$qrCode->getContentType());
//        echo $qrCode->writeString();
//        exit();
//    }
}
